package com.unohacha.qqj.fzdr.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.unohacha.qqj.fzdr.FindImageByImageActivity;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.SupplyDemandTypeActivity;
import com.unohacha.qqj.fzdr.SupplyDemandTypeActivity1;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.Constants;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeBannerBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeLatestBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeNeedBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeNewInfoBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeOpenProvinceBean;
import com.unohacha.qqj.fzdr.fragment.MaterialInfoActivity;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.ui.activity.AfterPubMatchActivity;
import com.unohacha.qqj.fzdr.ui.activity.CategoryActivity;
import com.unohacha.qqj.fzdr.ui.activity.SearchActivity;
import com.unohacha.qqj.fzdr.util.BroadCastReceiverUtil;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.fzdr.view.RecyclerDividerForOther;
import com.unohacha.qqj.fzdr.view.SpacesItemDecoration;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.unohacha.qqj.mylibrary.base.BaseFragment;
import com.unohacha.qqj.mylibrary.listener.PoponDismissListener;
import com.unohacha.qqj.mylibrary.view.ConfirmPopWindow;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页 碎片
 */
public class FirstPagerFragment extends BaseFragment implements OnRefreshListener, OnBannerListener, BroadCastReceiverUtil.OnReceiveBroadcast {

    @BindView(R.id.main_head_city)
    TextView mainHeadCity;
    @BindView(R.id.main_head_address)
    LinearLayout mainHeadAddress;
    @BindView(R.id.main_head_search)
    LinearLayout mainHeadSearch;
    @BindView(R.id.main_head_camera)
    TextView mainHeadCamera;
    @BindView(R.id.banner)
    Banner firstViewpager;
    @BindView(R.id.left_fz_ml)
    ImageView leftFzMl;
    @BindView(R.id.left_fz_type)
    TextView leftFzType;
    @BindView(R.id.left_frame_layout)
    FrameLayout leftFrameLayout;
    @BindView(R.id.right_fz_ml)
    ImageView rightFzMl;
    @BindView(R.id.right_fz_type)
    TextView rightFzType;
    @BindView(R.id.right_frame_layout)
    FrameLayout rightFrameLayout;
    @BindView(R.id.down_fz_ml_left)
    ImageView downFzMlLeft;
    @BindView(R.id.down_fz_type_left)
    TextView downFzTypeLeft;
    @BindView(R.id.down_frame_layout_left)
    FrameLayout downFrameLayoutLeft;
    @BindView(R.id.down_fz_ml_center)
    ImageView downFzMlCenter;
    @BindView(R.id.down_fz_type_center)
    TextView downFzTypeCenter;
    @BindView(R.id.down_frame_layout_center)
    FrameLayout downFrameLayoutCenter;
    @BindView(R.id.down_fz_ml_right)
    ImageView downFzMlRight;
    @BindView(R.id.down_fz_type_right)
    TextView downFzTypeRight;
    @BindView(R.id.down_frame_layout_right)
    FrameLayout downFrameLayoutRight;
    @BindView(R.id.look_life_more)
    TextView lookLifeMore;
    @BindView(R.id.recycler_corner)
    RecyclerView recyclerCorner;
    @BindView(R.id.latest_recomm_recycler)
    RecyclerView latestRecommRecycler;
    @BindView(R.id.look_recomm_more)
    TextView lookRecommMore;
    @BindView(R.id.text_title)
    TextView textTitle;
    @BindView(R.id.latest_content_tv)
    TextView latestContentTv;
    @BindView(R.id.look_latest_more)
    TextView lookLatestMore;
    @BindView(R.id.news_info_iv)
    ImageView newsInfoIv;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private List<HomeNeedBean.DataEntity> mHomeDataList = new ArrayList<>();//纺织生态圈的集合
    private List<HomeAppBean.DataEntity> mHomeAppList = new ArrayList<>();//我的应用的集合
    private List<HomeLatestBean.DataEntity> mHomeLatestList = new ArrayList<>();//最新推荐
    private List<HomeBannerBean.DataBean> mHomeBannerList = new ArrayList<>();//首页banner
    private List<String> slideImages = new ArrayList<>();
    private BaseRVAdapter myBaseAppAdater;
    private BaseActivity baseActivity;
    private BaseRVAdapter mBaseLatestAdapter;
    private String address_id = "12685";//定位后的或者选择后的地址id ,默认先写余杭区
    private List<HomeOpenProvinceBean.DataEntity> openProList = new ArrayList<>();//开放城市的列表
    private BroadcastReceiver broadcastReceiver;//为了address_id

    @Override
    protected void initBundle(Bundle arguments) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_first_page_layout;
    }

    @Override
    protected void initView(View rootView) {
        baseActivity = (BaseActivity) getActivity();
        if (!TextUtils.isEmpty(Prefer.getInstance().getLocationName())) {
            mainHeadCity.setText(Prefer.getInstance().getLocationName());
        }else {
            mainHeadCity.setText("选择区域");
        }
        if (!TextUtils.isEmpty(Prefer.obtainReLocation(getContext()))){
            address_id = Prefer.obtainReLocation(getContext());
        }
        broadcastReceiver = BroadCastReceiverUtil.registerBroadcastReceiver(baseActivity,new String[]{Constants.ACTION_UPTATE_LOCATION},this);
        setViewPagerConfig();
        getHomeNeedInfo();//纺织生态圈
        getMyAppData();//我的应用
        getMyLatestInfomation();//最新推荐
        getNewsInfoData();//最新资讯
        getAdList();
        getOpenProvience();
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(Prefer.getInstance().getLocationName())) {
            mainHeadCity.setText(Prefer.getInstance().getLocationName());
        }else {
            mainHeadCity.setText("选择区域");
        }
        if (!TextUtils.isEmpty(Prefer.obtainReLocation(getContext()))){
            address_id = Prefer.obtainReLocation(getContext());
        }
    }

    //获取开放城市
    private void getOpenProvience(){
        XUtil.Post(UrlConfig.OPEN_PROVIENCE,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        HomeOpenProvinceBean provinceBean = gson.fromJson(result,HomeOpenProvinceBean.class);
                        if (null != provinceBean){
                            if (0 != openProList.size()){
                                openProList.clear();
                            }
                            openProList.addAll(provinceBean.getData());
                            getAddressID(openProList);
                            if (TextUtils.isEmpty(Prefer.obtainReLocation(getContext()))){

                                if (null == baseActivity.confirmPop){
                                    baseActivity.confirmPop = new ConfirmPopWindow(baseActivity,baseActivity);
                                }
                                baseActivity.confirmPop.showUi("当前城市不在开通范围内,是否切换?","否","是");
                                baseActivity.confirmPop.showAtLocation(mainHeadAddress, Gravity.CENTER,0,0);
                                baseActivity.confirmPop.setConfirmListener(new ConfirmPopWindow.OnConfirmListener() {
                                    @Override
                                    public void onSure() {
                                        //跳转至切换城市界面
                                        jumpToOtherActivity(getContext(),RegionLocateActivity.class);
                                    }

                                    @Override
                                    public void onCancel() {
                                        MyToast(getContext(),"取消");
                                        baseActivity.confirmPop.dismissView();
                                    }
                                });
                                baseActivity.confirmPop.setOnDismissListener(new PoponDismissListener(baseActivity));
                            }

                        }
                    }else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //从集合中查出与定位匹配的addressID
    private void getAddressID(List<HomeOpenProvinceBean.DataEntity> mDataList){
        String locationPro = Prefer.getInstance().obtainProCity(getContext());
        String province = locationPro.substring(0, Prefer.obtainProCity(getContext()).indexOf(","));
        String city = locationPro.substring(
                locationPro.indexOf(",") + 1,
                locationPro.length());
        String district = Prefer.obtainProRegion(getContext());


        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).getName().equals(province)){//省
                for (int j = 0; j < mDataList.get(i).getCity().size() ; j++) {//市
                    if (mDataList.get(i).getCity().get(j).getName().equals(city)){
                        for (int k = 0; k < mDataList.get(i).getCity().get(j).getRea().size(); k++) {//区
                            if (mDataList.get(i).getCity().get(j).getRea().get(k).getName().equals(district)){
                                address_id = mDataList.get(i).getCity().get(j).getRea().get(k).getId() + "";
                                Prefer.saveReLoaction(getContext(),address_id);
                                Prefer.setLocationName(mDataList.get(i).getCity().get(j).getRea().get(k).getName());
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 纺织生态圈
     */
    private void getHomeNeedInfo() {
        baseActivity.showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        XUtil.Post(UrlConfig.HOME_NEED_INFO, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeNeedBean homeNeedBean = gson.fromJson(result, HomeNeedBean.class);
                        if (0 != mHomeDataList.size()) {
                            mHomeDataList.clear();
                        }
                        if (null != homeNeedBean) {
                            mHomeDataList.addAll(homeNeedBean.getData());
                        }

                        setHomeNeedData();
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getContext(), getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(getContext(), jsonObject.optString("message"));
                    }
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.finishLoadmoreWithNoMoreData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                baseActivity.hideLoading();
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                baseActivity.hideLoading();
                super.onFinished();
            }
        });
    }

    /**
     * 我的应用
     */
    private void getMyAppData() {
        baseActivity.showLoading();
        XUtil.Post(UrlConfig.HOME_MY_APP, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeAppBean homeAppBean = gson.fromJson(result, HomeAppBean.class);
                        if (0 != mHomeAppList.size()) {
                            mHomeAppList.clear();
                        }

                        if (null != homeAppBean) {
                            mHomeAppList.addAll(homeAppBean.getData());
                            setMyAppData();
                        }
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getContext(), getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(getContext(), jsonObject.optString("message"));
                    }
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.finishLoadmoreWithNoMoreData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                baseActivity.hideLoading();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                baseActivity.hideLoading();
                super.onError(ex, isOnCallback);
            }
        });
    }

    /**
     * 最新推荐
     */
    private void getMyLatestInfomation() {
        baseActivity.showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("address_id", address_id);//固定数据 先写余杭区
        XUtil.Post(UrlConfig.HOME_LATEST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeLatestBean homeLatestBean = gson.fromJson(result, HomeLatestBean.class);

                        if (0 != mHomeLatestList.size()) {
                            mHomeLatestList.clear();
                        }
                        if (null != homeLatestBean) {
                            mHomeLatestList.addAll(homeLatestBean.getData());
                            setMyLatestData();
                        }


                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(baseActivity, getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(baseActivity, jsonObject.optString("message"));
                    }
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.finishLoadmoreWithNoMoreData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                baseActivity.hideLoading();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                baseActivity.hideLoading();
                super.onError(ex, isOnCallback);
            }
        });
    }


    //最新资讯
    private void getNewsInfoData() {
        Map<String, Object> params = new HashMap<>();
        params.put("typeid", 0);//类型(0: 最新资讯, 1: 本地资讯)
        params.put("address_id", address_id);
        XUtil.Post(UrlConfig.HOME_LATEST_INFO, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeNewInfoBean homeNewInfoBean = gson.fromJson(result, HomeNewInfoBean.class);
                        if (null != homeNewInfoBean) {
                            setNewsInfoData(homeNewInfoBean);
                        }
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(baseActivity, getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(baseActivity, jsonObject.optString("message"));
                    }
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.finishLoadmoreWithNoMoreData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置纺织生态圈数据
    private void setHomeNeedData() {
        if (0 != mHomeDataList.size()) {
            Glide.with(this).load(mHomeDataList.get(0).getThumb()).into(leftFzMl);
            leftFzType.setText(mHomeDataList.get(0).getName());

            Glide.with(this).load(mHomeDataList.get(1).getThumb_rectangle()).into(rightFzMl);
            rightFzType.setText(mHomeDataList.get(1).getName());

            Glide.with(this).load(mHomeDataList.get(2).getThumb_small_square()).into(downFzMlLeft);
            downFzTypeLeft.setText(mHomeDataList.get(2).getName());

            Glide.with(this).load(mHomeDataList.get(3).getThumb_small_square()).into(downFzMlCenter);
            downFzTypeCenter.setText(mHomeDataList.get(3).getName());

            Glide.with(this).load(mHomeDataList.get(4).getThumb_small_square()).into(downFzMlRight);
            downFzTypeRight.setText(mHomeDataList.get(4).getName());
            
        }
    }

    
    
    //设置我的应用
    private void setMyAppData() {
        recyclerCorner.setLayoutManager(new GridLayoutManager(baseActivity, 4));
        myBaseAppAdater = new BaseRVAdapter(baseActivity, mHomeAppList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_my_app;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView my_app_logo = holder.getImageView(R.id.my_app_logo);
                TextView my_app_name = holder.getTextView(R.id.my_app_name);
                if (0 != mHomeAppList.size()) {
                    Glide.with(getActivity()).load(mHomeAppList.get(position).getImg()).into(my_app_logo);
                    my_app_name.setText(mHomeAppList.get(position).getName());
                }
            }

        };
        recyclerCorner.setAdapter(myBaseAppAdater);
        myBaseAppAdater.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if (getResources().getString(R.string.material_info).equals(mHomeAppList.get(position).getName())) {
                    Intent intent = new Intent(baseActivity,MaterialActivity.class);
                    intent.putExtra("app_cate_id",mHomeAppList.get(position).getId());
                    intent.putExtra("address_id",address_id);
                    startActivity(intent);
                } else if (getResources().getString(R.string.logistics_info).equals(mHomeAppList.get(position).getName())){
                    ToastUtils.showT("暂未开放，敬请期待");
//                    Intent intent = new Intent(baseActivity, MaterialInfoActivity.class);
//                    startActivity(intent);
                } else if (getResources().getString(R.string.express_look).equals(mHomeAppList.get(position).getName())){
                    Intent intent = new Intent(baseActivity,ExpressLookActivity.class);
                    startActivity(intent);
                } else if (getResources().getString(R.string.exhibition_info).equals(mHomeAppList.get(position).getName())){
//                    ToastUtils.showT("暂未开放，敬请期待");
                    Intent intent = new Intent(baseActivity,ExhibitionInfoActivity.class);
                    startActivity(intent);
                } else if (getResources().getString(R.string.fz_school).equals(mHomeAppList.get(position).getName())){
                    Intent intent = new Intent(baseActivity,FzSchoolActivity.class);
                    startActivity(intent);
                } else if (getResources().getString(R.string.fz_standard).equals(mHomeAppList.get(position).getName())){
                    Intent intent = new Intent(baseActivity,FzStandardActivity.class);
                    startActivity(intent);
                } else if (getResources().getString(R.string.sj_area).equals(mHomeAppList.get(position).getName())){
//                    ToastUtils.showT("暂未开放，敬请期待");
                    Intent intent = new Intent(baseActivity,SellerAreaActivity.class);
                    startActivity(intent);
                } else if (getResources().getString(R.string.locate_yellow_page).equals(mHomeAppList.get(position).getName())){
                    Intent intent = new Intent(baseActivity,LocationYPageActivity.class);
                    startActivity(intent);
                }
            }
        });

        myBaseAppAdater.notifyDataSetChanged();
    }

    //设置最新推荐数据
    private void setMyLatestData() {
        mBaseLatestAdapter = new BaseRVAdapter(baseActivity, mHomeLatestList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_home_latest_tj;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView latest_iv = holder.getImageView(R.id.latest_iv);
                TextView latest_title = holder.getTextView(R.id.latest_title);
                ImageView logo_iv = holder.getImageView(R.id.logo_iv);
                TextView logo_name = holder.getTextView(R.id.logo_name);
                TextView tj_type = holder.getTextView(R.id.tj_type);
                TextView type_show = holder.getTextView(R.id.type_show);
                if (0 != mHomeLatestList.size()) {
                    Glide.with(baseActivity).load(mHomeLatestList.get(position).getList_pic()).into(latest_iv);
                    if (!TextUtils.isEmpty(mHomeLatestList.get(position).getThumb())) {
                        Glide.with(baseActivity).load(mHomeLatestList.get(position).getThumb()).into(logo_iv);
                    } else {
                        logo_iv.setImageResource(R.drawable.ic_default_photo);
                    }
                    latest_title.setText(mHomeLatestList.get(position).getTitle());
                    logo_name.setText(mHomeLatestList.get(position).getNumber_no());

                    if(1 == mHomeLatestList.get(position).getTypeid()){
                        type_show.setText("供");
                        type_show.setTextColor(getResources().getColor(R.color.green1ccf70));
                    }else {
                        type_show.setText("求");
                        type_show.setTextColor(getResources().getColor(R.color.text_color_red));
                    }
                    
                    if (!TextUtils.isEmpty(chekType(mHomeLatestList.get(position).getOne_pid()))) {
                        tj_type.setText("<" + chekType(mHomeLatestList.get(position).getOne_pid()) + ">");
                    }else {
                        tj_type.setText(" ");
                    }
                }
            }
        };

        latestRecommRecycler.setAdapter(mBaseLatestAdapter);
        mBaseLatestAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(getContext(),CommonSDActivity.class);
                if(1 == mHomeLatestList.get(position).getTypeid()){//推荐类型--供
                    intent.putExtra("recommended_type","1");
                }else {//推荐类型--求
                    intent.putExtra("recommended_type","2");
                }
                
                intent.putExtra("supply_cate_id",mHomeLatestList.get(position).getSupply_cate_id());
                intent.putExtra("member_id",mHomeLatestList.get(position).getMember_id() + "");
                intent.putExtra("title",chekType(mHomeLatestList.get(position).getOne_pid()));
                startActivity(intent);
            }
        });

        mBaseLatestAdapter.notifyDataSetChanged();
    }

    //通过Id来检测是什么类型，共有12种类型
    private String chekType(int typeId){
       String type = "";
       switch (typeId){
           case 1:
               type = "面料";
               break;
           case 2:
               type = "织造";
               break;
           case 3:
               type = "原料";
               break;
           case 4:
               type = "招聘";
               break;
           case 5:
               type = "求职";
               break;
           case 6:
               type = "租赁";
               break;
           case 7:
               type = "设备";
               break;
           case 8:
               type = "维修";
               break;
           case 9:
               type = "库存";
               break;
           case 10:
               type = "辅料";
               break;
           case 11:
               type = "处理";
               break;
           case 12:
               type = "其他";
               break;
       }
       return type;
    }
    
    //设置最新资讯
    private void setNewsInfoData(HomeNewInfoBean homeNewInfoBean) {
        if (null != homeNewInfoBean){
            Glide.with(baseActivity).load(homeNewInfoBean.getData().getThumb()).into(newsInfoIv);
            textTitle.setText(homeNewInfoBean.getData().getTitle());
            latestContentTv.setText(homeNewInfoBean.getData().getContent());

        }
    }

    //获取广告列表数据
    private void getAdList(){
        Map<String,Object> params = new HashMap<>();
        params.put("typeid",3);//3.轮播图
        XUtil.Post(UrlConfig.AD_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        HomeBannerBean bannerBean = gson.fromJson(result,HomeBannerBean.class);
                        if (null != bannerBean){
                            if (0 != mHomeBannerList.size()){
                                mHomeBannerList.clear();
                            }

                            for (int i = 0; i < bannerBean.getData().size(); i++) {
                                slideImages.add(i, bannerBean.getData().get(i).getImg_face());
                            }

                            mHomeBannerList.addAll(bannerBean.getData());
                            firstViewpager.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置圆形指示器与标题
                            firstViewpager.setIndicatorGravity(BannerConfig.CENTER);//设置指示器位置
                            firstViewpager.setImages(slideImages);
                            firstViewpager.setImageLoader(new GlideImageLoader());
                            firstViewpager.start();
                        }
                    }else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @OnClick({R.id.main_head_address, R.id.main_head_search, R.id.main_head_camera,
            R.id.left_fz_ml, R.id.right_fz_ml, R.id.down_fz_ml_left, R.id.down_fz_ml_center,
            R.id.down_fz_ml_right,R.id.look_life_more})
    public void onViewClicked(View view) {
        Intent intent = new Intent(getContext(),CommonSDActivity.class);
        switch (view.getId())
        {
            case R.id.main_head_address://右上角地址

                //跳转至切换城市界面
                jumpToOtherActivity(getContext(),RegionLocateActivity.class);
                break;
            case R.id.main_head_search://搜索
                Intent intent1=new Intent(getContext(), SearchActivity.class);
                startActivity(intent1);
                break;
            case R.id.main_head_camera://以图找图
                jumpToOtherActivity(getContext(), FindImageByImageActivity.class);
                break;
            case R.id.left_fz_ml://纺织生态圈 图1
                Prefer.getInstance().setEcosphere(1);//保存 查看详情时调用
                intent.putExtra("supply_cate_id",mHomeDataList.get(0).getId());
                intent.putExtra("member_id",Prefer.getInstance().getUser_id());
                intent.putExtra("title",mHomeDataList.get(0).getName());
                intent.putExtra("recommended_type","1");
                startActivity(intent);
                break;
            case R.id.right_fz_ml://纺织生态圈 图2
                Prefer.getInstance().setEcosphere(2);//保存 查看详情时调用
                intent.putExtra("supply_cate_id",mHomeDataList.get(1).getId());
                intent.putExtra("member_id",Prefer.getInstance().getUser_id());
                intent.putExtra("title",mHomeDataList.get(1).getName());
                intent.putExtra("recommended_type","1");
                startActivity(intent);
                break;
            case R.id.down_fz_ml_left://图3
                Prefer.getInstance().setEcosphere(3);//保存 查看详情时调用
                intent.putExtra("supply_cate_id",mHomeDataList.get(2).getId());
                intent.putExtra("member_id",Prefer.getInstance().getUser_id());
                intent.putExtra("title",mHomeDataList.get(2).getName());
                intent.putExtra("recommended_type","1");
                startActivity(intent);
                break;
            case R.id.down_fz_ml_center://图4
                intent.putExtra("supply_cate_id",mHomeDataList.get(3).getId());
                intent.putExtra("member_id",Prefer.getInstance().getUser_id());
                intent.putExtra("title",mHomeDataList.get(3).getName());
                intent.putExtra("recommended_type","1");
                startActivity(intent);
                break;
            case R.id.down_fz_ml_right://图5
                intent.putExtra("supply_cate_id",mHomeDataList.get(4).getId());
                intent.putExtra("member_id",Prefer.getInstance().getUser_id());
                intent.putExtra("title",mHomeDataList.get(4).getName());
                intent.putExtra("recommended_type","1");
                startActivity(intent);
                break;
            case R.id.look_life_more:
                Intent intent3 = new Intent(getContext(), SupplyDemandTypeActivity1.class);
                intent3.putExtra("type","3");
                startActivity(intent3);
                break;
        }
        
    }
    
    /**
     * 设置ViewPager属性
     */
    private void setViewPagerConfig() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(baseActivity));
        firstViewpager.setOnBannerListener(this);
        latestRecommRecycler.setLayoutManager(new GridLayoutManager(baseActivity,2));
        //添加ItemDecoration，item之间的间隔
        int leftRight = dip2px(15);
        int topBottom = dip2px(15);

        latestRecommRecycler.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
    }
    
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                getHomeNeedInfo();//纺织生态圈
                getMyAppData();//我的应用
                getMyLatestInfomation();//最新推荐
                getNewsInfoData();//最新资讯
            }
        },2000);
    }
    
    @Override
    public void OnBannerClick(int position) {

    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (null != intent){
            String action = intent.getAction();
            switch (action){
                case Constants.ACTION_UPTATE_LOCATION:
                    String name = intent.getStringExtra("name");
                    String id = intent.getStringExtra("address_id");
                    if (!TextUtils.isEmpty(intent.getStringExtra("address_id"))){
                        address_id = intent.getStringExtra("address_id");
                        Prefer.saveReLoaction(getContext(),address_id);
                        Prefer.setLocationName(name);//保存选择的地区名字
                        getMyLatestInfomation();//刷新最新推荐数据
                        getNewsInfoData();//刷新资讯信息
                        mainHeadCity.setText(name);
                    }
                    break;
            }
        }
    }

    public int dip2px(float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        BroadCastReceiverUtil.unRegisterBroadcastReceiver(baseActivity,broadcastReceiver);
    }
}
